package qiniu.ip17mon;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.Key;
import java.security.MessageDigest;

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class SecretUtil {

	public static final String TYPE_AES = "aes";
	public static final String TYPE_DES = "des";
	public static final String HMAC_MD5 = "HmacMD5";
	public static final String HMAC_SHA1 = "HmacSha1";
	
	private SecretUtil(){
	}
	
	/**
	 * 将字符串进行 sha1 摘要
	 * @param str
	 * @return
	 * @throws Exception
	 */
	public static String digestSha1(String str) throws Exception{
		MessageDigest md = MessageDigest.getInstance("sha1");//md5
		md.update(str.getBytes());
		return toHexString(md.digest());
	}
	
	/**
	 * 将字符串进行 md5 摘要
	 * @param str
	 * @return
	 * @throws Exception
	 */
	public static String digestMd5(String str) throws Exception{
		MessageDigest md = MessageDigest.getInstance("md5");//md5
		md.update(str.getBytes("utf-8"));
		return toHexString(md.digest());
	}
	
	/**
	 * 将文件进�?sha1 摘要
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public static String digestFile(File file) throws Exception{
		InputStream is = null;
		DigestInputStream dis = null;
		MessageDigest md = MessageDigest.getInstance("sha1");//md5
		try{
			is = new FileInputStream(file);
			dis = new DigestInputStream(is,md);
			byte[] buf = new byte[1024];
			//即使不用，也�?��将该流读�?��
			while(dis.read(buf) != -1){
			}
		}finally{
			IOUtils.closeQuietly(dis);
			IOUtils.closeQuietly(is);
		}
		return toHexString(md.digest());
	}
	
	/**
	 * 使用jasypt加密
	 * @param content
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String jasyptSymmetry(String content,String key) throws Exception{
		BasicTextEncryptor enc = new BasicTextEncryptor();
		enc.setPassword(key);
		return enc.encrypt(content);
	}
	
	/**
	 * 使用jasypt解密
	 * @param content
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String jasyptDecrypt(String content,String key) throws Exception{
		BasicTextEncryptor enc = new BasicTextEncryptor();
		enc.setPassword(key);
		return enc.decrypt(content);
	}
	
	/**
	 * 对称加密
	 * @param type
	 * @param content
	 * @param keys
	 * @return
	 * @throws Exception
	 */
	public static byte[] symmetryEncrypt(String type,byte[] content,byte[] keys) throws Exception{
		Cipher encryptCipher = Cipher.getInstance(type);
		encryptCipher.init(Cipher.ENCRYPT_MODE,getKey(keys,type));
		return encryptCipher.doFinal(content);
	}
	
	/**
	 * 对称解密
	 * @param type	可�?值为常量：TYPE_...
	 * @param content
	 * @param keys
	 * @return
	 * @throws Exception
	 */
	public static byte[] decryptEncrypt(String type,byte[] content,byte[] keys) throws Exception{
		Cipher decryptCipher = Cipher.getInstance(type);
		decryptCipher.init(Cipher.DECRYPT_MODE,getKey(keys,type));
		return decryptCipher.doFinal(content);
	}
	
	/**
	 * HMAC加密
	 * @param type	可�?值为常量：HMAC_....
	 * @param content
	 * @param keys
	 * @return
	 * @throws Exception
	 */
	public static String encryptHMAC(String type,byte[] content,byte[] keys) throws Exception {
		SecretKey secretKey = new SecretKeySpec(keys,type);
		Mac mac = Mac.getInstance(secretKey.getAlgorithm());
		mac.init(secretKey);
		return toHexString(mac.doFinal(content));
	}
	
	/*
	 * 根据指定的密钥字符串(密码)生成密钥，所�?es长度�?位，aes长度�?6位，不足�?，超出只取前面的
	 * @param keyStr
	 * @return
	 */
	private static Key getKey(byte[] keyBytes,String type){
		int len = "des".equalsIgnoreCase(type) ? 8 : 16;
		byte[] array = new byte[len];
		System.arraycopy(keyBytes,0,array,0,Math.min(keyBytes.length,len));
		Key key = new SecretKeySpec(array,type);
		return key;
	}
	
	/*
	 * 把  byte[] 转换成16进制字符串
	 * @param pb
	 * @return
	 */
	private static String toHexString(byte[] pb){
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < pb.length; i++) {
			int val = pb[i] & 0xff;
			if (val < 0x10) {
				sb.append('0');
			}
			sb.append(Integer.toHexString(val));
		}
		return sb.toString();
	}
    
    public static final String bytesToBase64(byte[] bArray) {  
        if( bArray == null ) {  
            return "";  
        }  
        String str = new BASE64Encoder().encode(bArray);
        return str;  
    }

	public static byte[] base64ToBytes(String str) throws IOException {
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] bytes = decoder.decodeBuffer(str);
		return bytes;
	}  
	
	public static byte[] decode(String str) throws Exception{
		byte[] bytes = null;
		BASE64Decoder decoder = new BASE64Decoder();
		bytes = decoder.decodeBuffer(str);
		return bytes;
	}
	
	public static String encode(byte[] bytes){
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(bytes);
	}
	
}
